package com.sibrary.booxoo;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.Browser;
import android.provider.Browser.BookmarkColumns;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.sibrary.booxoo.download.BooxooDownloadController;
import com.sibrary.booxoo.download.BooxooDownloadItem;
import com.sibrary.components.CustomWebView;
import com.sibrary.components.CustomWebViewClient;
import com.sibrary.utils.Constants;
import com.sibrary.utils.DomUtils;

public class BooxooMainActivity extends Activity {

	public static long threadid = 0;

	private List<CustomWebView> mWebViews;
	private List<String> mUrls; // 书签列表

	private ProgressBar mUrlProgressBar;
	private EditText mUrlEditText;
	private Button mUrlButton;
	private Button prevButton;
	private Button nextButton;
	private LayoutInflater mInflater;
	private ViewFlipper mViewFlipper;

	private CustomWebView mCurrentWebView; // 当前显示的窗口
	private LinearLayout mUrlTitleBarLayout;

	// requestCode
	static final int BOOKMARKS_SHOW_REQUEST_CODE = 0;
	static final int BOOKMARKS_ADD_REQUEST_CODE = 1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.booxoo_main_activity);

		threadid = Thread.currentThread().getId();

		initBooxooSomeSource();

		addTab(true, -1);

		mUrlEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				mUrlEditText.selectAll();
			}
		});

		mUrlEditText.setOnKeyListener(new View.OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if (keyCode == KeyEvent.KEYCODE_ENTER) {
					String urlText = mUrlEditText.getText().toString();
					mCurrentWebView.loadUrl(urlText);
				}
				return false;
			}
		});

		mUrlButton.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String urlText = mUrlEditText.getText().toString();
				mCurrentWebView.loadUrl(urlText);
			}
		});

		prevButton.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				int total = mViewFlipper.getChildCount();
				int index = mViewFlipper.getDisplayedChild();
				if (total > 1 && (index > 0 && index < total)) {
					mViewFlipper.setDisplayedChild(index - 1);
					mCurrentWebView = mWebViews.get(index - 1);

					setUrlTitleBarVisibilityWithCurrentWebView();
					updateUrlEdit();
				}
			}
		});

		nextButton.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				int total = mViewFlipper.getChildCount();
				int index = mViewFlipper.getDisplayedChild();
				if (total > 1 && (index >= 0 && index + 1 < total)) {
					mViewFlipper.setDisplayedChild(index + 1);
					mCurrentWebView = mWebViews.get(index + 1);

					setUrlTitleBarVisibilityWithCurrentWebView();
					updateUrlEdit();
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.booxoo_main_activity, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.menu_input_url:
			setUrlTitleBarVisibility(true);
			// mUrlEditText.requestFocus();
			break;
		case R.id.menu_add_bookmarks: {

			String url = mCurrentWebView.getUrl();
			String title = mCurrentWebView.getTitle();

			if (isUrlExist(url)) {
				String text = "The bookmark already exists";
				Toast.makeText(BooxooMainActivity.this, text,
						Toast.LENGTH_SHORT).show();
				break;
			}

			Intent intent = new Intent();
			intent.putExtra("bookmarksUrl", url);
			intent.putExtra("bookmarksTitle", title);
			intent.setClass(BooxooMainActivity.this,
					BooxooBookmarksAddActivity.class);

			startActivityForResult(intent, BOOKMARKS_ADD_REQUEST_CODE);
			break;
		}
		case R.id.menu_show_bookmarks: {
			Intent intent = new Intent();
			intent.setClass(BooxooMainActivity.this,
					BooxooBookmarksActivity.class);

			startActivityForResult(intent, BOOKMARKS_SHOW_REQUEST_CODE);
			break;
		}
		case R.id.menu_show_download: {
			Intent intent = new Intent();
			intent.setClass(BooxooMainActivity.this,
					BooxooDownloadActivity.class);

			startActivity(intent);
			break;
		}
		case R.id.menu_show_config: {
			Intent intent = new Intent();
			intent.setClass(BooxooMainActivity.this,
					BooxooSettingsPreferenceActivity.class);

			startActivity(intent);
			break;
		}
		case R.id.menu_app_exit:
			finish();
			break;
		default:
			finish();
			break;
		}

		return true;
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case BOOKMARKS_SHOW_REQUEST_CODE: {
			if (data != null) {
				Bundle bundle = data.getExtras();
				String bookmarksUrl = bundle.getString("bookmarksUrl");
				mCurrentWebView.loadUrl(bookmarksUrl);
			}
			break;
		}
		case BOOKMARKS_ADD_REQUEST_CODE: {
			if (data != null) {
				notifyUrlsChanged();
			}
			break;
		}
		default:
			break;
		}
	}

	private void initBooxooSomeSource() {
		mWebViews = new ArrayList<CustomWebView>();
		mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mViewFlipper = (ViewFlipper) findViewById(R.id.viewflipper);

		mUrlTitleBarLayout = (LinearLayout) findViewById(R.id.urlTitleBarLayout);

		mUrlProgressBar = (ProgressBar) findViewById(R.id.progressBar);
		mUrlEditText = (EditText) findViewById(R.id.urlEditText);
		mUrlButton = (Button) findViewById(R.id.okButton);

		prevButton = (Button) findViewById(R.id.prevButton);
		nextButton = (Button) findViewById(R.id.nextButton);

		// 初始化配置文件引用
		Constants.mSharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		
		// 初始化全局上下文引用
		Constants.mContext = getApplicationContext();

		// 查看是否有没有下载完的项目, 继续下载 (暂时还不是断点续传下载， 待实现)
		if (DomUtils.isExists()) {
			BooxooDownloadController.getInstance().mDownloads = DomUtils
					.parseXml();
			if (BooxooDownloadController.getInstance().mDownloads.size() > 0) {
				for (int i = 0; i < BooxooDownloadController.getInstance().mDownloads
						.size(); ++i) {
					if (!BooxooDownloadController.getInstance().mDownloads.get(
							i).getCancel()) {

						BooxooDownloadController.getInstance().mDownloadQueues
								.add(BooxooDownloadController.getInstance().mDownloads
										.get(i));
						BooxooDownloadController.getInstance().notifyStart();
					}
				}
			}
		}
	}

	private void initializeCurrentWebView() {
		mCurrentWebView.setWebViewClient(new CustomWebViewClient(this));
		// mCurrentWebView.setOnTouchListener(this);

		mCurrentWebView.setWebChromeClient(new WebChromeClient() {

			public void onProgressChanged(WebView view, int progress) {
				((CustomWebView) view).setProgress(progress);
				mUrlProgressBar.setProgress(mCurrentWebView.getProgress());
			}

			@Override
			public boolean onCreateWindow(WebView view, final boolean dialog,
					final boolean userGesture, final Message resultMsg) {

				WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;

				addTab(false, mViewFlipper.getDisplayedChild());

				transport.setWebView(mCurrentWebView);
				resultMsg.sendToTarget();

				return true;
			}
		});

		mCurrentWebView.setDownloadListener(new DownloadListener() {

			@Override
			public void onDownloadStart(String url, String userAgent,
					String contentDisposition, String mimetype,
					long contentLength) {
				// TODO Auto-generated method stub
				if (!isSDCardExist()) {
					Toast.makeText(BooxooMainActivity.this,
							"No SD Card found.", Toast.LENGTH_SHORT).show();
					return;
				}

				if (url != null) {
					BooxooDownloadItem item = null;
					item = BooxooDownloadController.getInstance()
							.getItemOfSameUrlInDownloads(url);
					if (item != null) {
						if (item.getCancel()) { // FIXME: 取消后重新下载
							item.setCancel(false);
							BooxooDownloadController.getInstance()
									.addItem(item);
							BooxooDownloadController.getInstance().alterItem(
									item);
							BooxooDownloadController.getInstance()
									.notifyStart();

							Toast.makeText(BooxooMainActivity.this,
									"Re-download", Toast.LENGTH_SHORT).show();
						} else { // FIXME: 已经下载过的选项
							Toast.makeText(BooxooMainActivity.this,
									"Download item already exists",
									Toast.LENGTH_SHORT).show();
						}
					} else {
						item = new BooxooDownloadItem(url);
						BooxooDownloadController.getInstance().addItem(item);
						BooxooDownloadController.getInstance().saveItem(item);
						BooxooDownloadController.getInstance().notifyStart();

						Toast.makeText(BooxooMainActivity.this,
								"Add to download list", Toast.LENGTH_SHORT)
								.show();
					}
				}
			}
		});
	}

	private void addTab(boolean navigateToHome, int parentIndex) {

		RelativeLayout view = (RelativeLayout) mInflater.inflate(
				R.layout.booxoo_main_webview, mViewFlipper, false);
		mCurrentWebView = (CustomWebView) view.findViewById(R.id.webview);

		initializeCurrentWebView();

		synchronized (mViewFlipper) {
			if (parentIndex != -1) {
				mWebViews.add(parentIndex + 1, mCurrentWebView);
				mViewFlipper.addView(view, parentIndex + 1);
			} else {
				mWebViews.add(mCurrentWebView);
				mViewFlipper.addView(view);
			}

			mViewFlipper.setDisplayedChild(mViewFlipper.indexOfChild(view));
		}

		// updateUrlEdit();
		// updatePreviousNextTabViewsVisibility();
		//
		// mUrlEditText.clearFocus();
		//
		if (navigateToHome) {
			String homepage = Constants.mSharedPreferences.getString(
					Constants.PREFERENCE_KEY_HOMEPAGE,
					Constants.URL_ABOUT_BLANK);

			if (homepage != Constants.URL_ABOUT_BLANK) {
				mCurrentWebView.loadUrl(homepage);
			}
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (mCurrentWebView.canGoBack()) {
				mCurrentWebView.goBack();
				return true;
			} else {
				if (mViewFlipper.getChildCount() > 1) {
					mWebViews.remove(mCurrentWebView);
					mViewFlipper.removeViewAt(mViewFlipper.getDisplayedChild());

					int index = mViewFlipper.getDisplayedChild();
					mCurrentWebView = mWebViews.get(index);
					return true;
				}
			}
		}

		return super.onKeyDown(keyCode, event);
	}

	private void updateUrlEdit() {
		mUrlEditText.setText(mCurrentWebView.getUrl());
	}

	public void onPageStarted(String url) {
		mUrlEditText.setText(url);
		setUrlTitleBarVisibility(true);
	}

	public void onPageFinished(String url) {
		mUrlEditText.setText(url);
		setUrlTitleBarVisibility(false);
	}

	private void setUrlTitleBarVisibility(boolean flag) {
		if (!flag) {
			mUrlTitleBarLayout.setVisibility(View.INVISIBLE);
		} else {
			mUrlTitleBarLayout.setVisibility(View.VISIBLE);
		}
	}

	private void setUrlTitleBarVisibilityWithCurrentWebView() {
		if (mCurrentWebView.isPageLoading()) {
			setUrlTitleBarVisibility(true);
			mUrlProgressBar.setProgress(mCurrentWebView.getProgress());
		} else {
			setUrlTitleBarVisibility(false);
		}
	}

	/**
	 * 测试书签是否存在
	 * 
	 * @return
	 */
	private boolean isUrlExist(String url) {

		if (mUrls == null) {
			mUrls = new ArrayList<String>();
			bookmarksUrls();
		}

		return mUrls.contains(url);
	}

	/**
	 * 获取书签列表
	 */
	private void bookmarksUrls() {
		ContentResolver contentResolver = getContentResolver();
		Cursor cursor = contentResolver.query(Browser.BOOKMARKS_URI, null,
				null, null, null);
		while (cursor.moveToNext()) {
			if (cursor.getString(
					cursor.getColumnIndex(Browser.BookmarkColumns.BOOKMARK))
					.equals("1")) {

				mUrls.add(cursor.getString(cursor
						.getColumnIndex(BookmarkColumns.URL)));
			}
		}
	}

	/**
	 * 当urls变化后， 重新获取urls
	 */
	public void notifyUrlsChanged() {
		bookmarksUrls();
	}

	/**
	 * 检查sdcard是否存在
	 */
	private boolean isSDCardExist() {
		return (Environment.getExternalStorageState()
				.equals(Environment.MEDIA_MOUNTED));
	}
}
